import React, { useState, useEffect, useRef } from 'react';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { ProColumns, EditableProTable } from '@ant-design/pro-table';
import { Button, FormInstance, message } from 'antd';
import { ExclamationCircleOutlined, RedoOutlined } from '@ant-design/icons';
import { OptType } from '@/utils/constants';
import { 
  getGoodsListByPage, 
  getCategoryListByPage,
  getBrandListByPage,
  checkCategoryExist,
  updateCategory,
  getSpell
} from '@/services/stock-goods/api';
import GoodName from '@/components/Select/GoodName';
import { isNull, showMsg } from '@/utils/utils';

const OptForm: React.FC<any> = (props) => {
  const { 
    handleModalVisible, 
    handleAdd, 
    actionRef, 
    record = {}, 
    optType = OptType.ADD 
  } = props;
  const formRef = useRef<FormInstance>()

  const [newRecord, setNewRecord] = useState({
    id: (Math.random() * 1000000).toFixed(0)
  });

  // 品类列表
  const [categoryList, setCategoryList] = useState<STOCKGOODSAPI.CategoryItem[]>([]);

  // 品牌列表
  const [brandList, setBrandList] = useState<STOCKGOODSAPI.BrandItem[]>([]);

  // 商品列表
  const [goodsList, setGoodsList] = useState<STOCKGOODSAPI.GoodsItem[]>([]);

  const [dataSource, setDataSource] = useState<any[]>([]);
  // 新增数量
  const [newAddNums, setNewAddNums] = useState<number>(0);

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const [beforeEditName] = useState<string>(record.class_name);

  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const columns: ProColumns<any>[] = [
    {
      title: '品牌', 
      dataIndex: 'brand_name',
      editable: false,
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      renderFormItem: (form, record1) => {
        return <GoodName noStyle name1={`goods_name_${record1.recordKey}`} allowClear={false} scope='B' onChange={e => {
          // console.log('选中的商品', e, form, record1);
          const obj = {
            class_name: e.class_name,
            goods_id: e.goods_id,
            brand_name: e.brand_name,
            obj: e,
            id: record1.recordKey,
          }
          const result = dataSource.findIndex(item => item.id === record1.recordKey);
          if (result > -1) {
            dataSource[result] = obj;
            setDataSource(Object.assign([], dataSource))
          }
        }} />
      },
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false,
    },
    {
      title: '原归属品类',
      dataIndex: 'class_name',
      editable: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 50,
      render: (text, record, _, action) => [
        // !record.create_user_id ? <a
        //   key="editable"
        //   onClick={() => {
        //     action?.startEditable?.(record.id);
        //   }}
        // >
        //   编辑
        // </a> : null,
        !record.create_user_id ? <a
          key="delete"
          onClick={() => {
            if (!record.create_user_id) {
              setNewAddNums((prev) => {
                return prev - 1;
              });
            }
            setDataSource(dataSource.filter(item => item.create_user_id));
          }}
        >
          删除
        </a> : null
      ]
    }
  ];

  // 复原
  const onRestore = () => {
    setNewAddNums(0);
    if (optType === OptType.ADD) {
      setDataSource([]);
    } else {
      setDataSource(dataSource.filter(item => item.create_user_id));
    }
  }

  // 品类名称检查唯一性
  const onCategoryNameChange = async (value: string) => {
    try {
      if (!value) {
        return false;
      }
      const data: any = await checkCategoryExist({class_name: value});
      return data.is_exist === "1";
    } catch (error) {
      message.error(error?.data?.errmsg);
      return false;
    }
  }

  const init = () => {
    getCategoryListByPage({
      current: 1, 
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.CategoryItemList) => {
      setCategoryList(data.record_list || []);
    });
    getGoodsListByPage({
      current: 1, 
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.GoodsItemList) => {
      setGoodsList(data.record_list || []);
    });

    getBrandListByPage({
      current: 1, 
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.BrandItemList) => {
      setBrandList(data.record_list || []);
    });
  }

  // 查询商品是否有改动
  const checkChange = (list) => {
    const result = list.filter(item => (item.id).includes('new'));
    setNewAddNums(result.length);
  }

  useEffect(() => {
    if (optType === OptType.EDIT) {
      getGoodsListByPage({current: 1, pageSize: 10000, class_id: record.class_id}).then((data: STOCKGOODSAPI.GoodsItemList) => {
        const list = data?.record_list?.map(item => {
          return {
            ...item,
            id: item.goods_id
          }
        })
        setDataSource(list || []);
      });
    } else {
      setDataSource([]);
    }
    setNewAddNums(0);
  }, [optType]);

  useEffect(() => {
    init()
  }, []);

  return <ModalForm
      className="modal-form"
      width="80%"
      layout="horizontal"
      title="新增/编辑品类"
      visible
      formRef={formRef}
      modalProps={{
        maskClosable: false
      }}
      onVisibleChange={handleModalVisible}
      onFinish={async (value) => {
        console.log(value)
        // if (editableKeys.length > 0) {
        //   showMsg('您还有未保存的商品信息，请先保存！');
        //   return;
        // }
        const goods_list: STOCKGOODSAPI.GoodsItem[] = dataSource;
        value = Object.assign({}, value);

        if (optType === OptType.ADD) {
          // 新增
          const data: STOCKGOODSAPI.CategoryItem = await handleAdd(value as STOCKGOODSAPI.CategoryItem);
          // 新增品类成功
          if (data) {
            const params = {
              add_goods_ids: goods_list.map(item => item.goods_id),
              class_name: value.class_name,
              class_py: value.class_py,
              class_id: data.class_id
            }
            await updateCategory(params);
          } 
        } else {
          // 修改
          const params = {
            add_goods_ids: goods_list.map(item => item.goods_id),
            class_name: value.class_name,
            class_py: value.class_py,
            class_id: record.class_id
          }
          await updateCategory(params);
        }
        handleModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }}
      submitter={{
        searchConfig: {
          resetText: '取消',
          submitText: '确定'
        }
      }}
      >
      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true,
                message: '请输入分类名称'
              },
              {
                required: true,
                validator: async (rule, value) => {
                  if (optType === OptType.ADD || optType === OptType.EDIT && beforeEditName !== value) {
                    const isExsit = await onCategoryNameChange(value);
                    if (isExsit) {
                      return Promise.reject("分类已存在");
                    } 
                    return Promise.resolve();
                  }
                  return Promise.resolve();
                }
              }
            ]
          }
          label="分类名称"
          placeholder="请输入分类名称"
          width="md"
          name="class_name"
          validateTrigger="onBlur"
          fieldProps={{
            onBlur: async (e: any) => {
              const value = e.target.value
              if (value) {
               const { py } = await getSpell(value)
               formRef.current?.setFieldsValue({
                class_py: py
               })
              }
            }
          }}
          initialValue={record.class_name}
        />
        <ProFormText
          rules={
            [
              {
                required: true,
                message: '请输入检索码'
              }
            ]
          }
          label="检索码"
          placeholder="请输入检索码"
          width="md"
          name="class_py"
          initialValue={record.class_py}
        />
      </ProForm.Group>

      <EditableProTable<any>
        rowKey="id"
        rowClassName={(data: STOCKGOODSAPI.GoodsItem) => {
          if (data.id === clickRow){
            return 'tableRowClick';
          }
          if (!isNull(record.class_id) && (data.id).includes('new')) {
            return 'new-add';
          }
          return ''
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        bordered
        headerTitle={'调整品类下商品（可选）'}
        cardBordered
        className={'update-goods-table'}
        value={dataSource}
        onChange={e => {
          checkChange(e);
          setDataSource(e)
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'restore',
                label: <Button onClick={onRestore} type="primary" icon={<RedoOutlined />}>变更复原</Button>
              }
            ]
          }
        }}
        recordCreatorProps={
          {
            newRecordType: 'dataSource',
            record: () => ({
              id: `new_${Date.now()}`,
            }),
          }
        }
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete]
          },
          onChange: setEditableRowKeys,
          onValuesChange: (record, recordList) => {
            setDataSource(recordList)
          },
        }}
        toolBarRender={() => [
          <div>
            <span>新增：</span>
            <span style={{color: '#52C41A'}}>{newAddNums}</span>
            <span style={{paddingLeft: '20px'}}>总数：</span>
            <span style={{color: '#2E8DE6'}}>{dataSource.length}</span>
          </div>
        ]}
        columns={columns}
      />
      <div className="modal-tips">
        <ExclamationCircleOutlined />
        <span>编辑品类和调整品类下商品信息后，请点击下方<strong>确定</strong>按钮保存结果</span>
      </div>
    </ModalForm>
}
export default OptForm;
